package com.cenntro.oss.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cenntro.auth.utils.AgentPathUtil;
import com.cenntro.common.base.BaseController;
import com.cenntro.common.model.vo.PageVO;
import com.cenntro.common.util.ConvertorUtils;
import com.cenntro.common.util.result.PageResult;
import com.cenntro.common.util.result.Result;
import com.cenntro.oss.mapper.DevBatteryMapper;
import com.cenntro.oss.mapper.DevBatteryPackMapper;
import com.cenntro.oss.model.dbo.AfterFaultDO;
import com.cenntro.oss.model.dbo.AfterFaultPartsDO;
import com.cenntro.oss.model.dbo.DevBatteryDO;
import com.cenntro.oss.model.dbo.DevBatteryModuleDO;
import com.cenntro.oss.model.dbo.DevBatteryPackDO;
import com.cenntro.oss.model.dbo.DevBomPartpnRefDO;
import com.cenntro.oss.model.dbo.DevCarDO;
import com.cenntro.oss.model.dbo.DevCertificateDO;
import com.cenntro.oss.model.dbo.DevDeviceOnlineDO;
import com.cenntro.oss.model.dbo.DevDevicePartsDO;
import com.cenntro.oss.model.dbo.DevDeviceStaticDO;
import com.cenntro.oss.model.dbo.SysAgentDO;
import com.cenntro.oss.model.qo.DevListQO;
import com.cenntro.oss.model.qo.DeviceCarListMapQO;
import com.cenntro.oss.model.qo.DeviceListQO;
import com.cenntro.oss.model.vo.AfterFaultPartsVO;
import com.cenntro.oss.model.vo.AfterFaultVO;
import com.cenntro.oss.model.vo.CarListVO;
import com.cenntro.oss.model.vo.DeivceDetailsVO;
import com.cenntro.oss.model.vo.DeivceListVO;
import com.cenntro.oss.model.vo.DevBatteryModuleVO;
import com.cenntro.oss.model.vo.DevBatteryPackVO;
import com.cenntro.oss.model.vo.DevBatteryVO;
import com.cenntro.oss.model.vo.DevCertificateVO;
import com.cenntro.oss.model.vo.DevDevicePartsVO;
import com.cenntro.oss.model.vo.DeviceCarListMapVO;
import com.cenntro.oss.model.vo.DeviceDataCountVO;
import com.cenntro.oss.model.vo.DeviceListVO;
import com.cenntro.oss.model.vo.DeviceStaticVO;
import com.cenntro.oss.model.vo.NewVehicleDetailVO;
import com.cenntro.oss.model.vo.VehicleDetailVO;
import com.cenntro.oss.model.vo.VehicleInsertVO;
import com.cenntro.oss.model.vo.VehicleVO;
import com.cenntro.oss.service.AfterFaultPartsService;
import com.cenntro.oss.service.AfterFaultService;
import com.cenntro.oss.service.DevBatteryModuleService;
import com.cenntro.oss.service.DevBomCarService;
import com.cenntro.oss.service.DevBomPartpnRefService;
import com.cenntro.oss.service.DevCarService;
import com.cenntro.oss.service.DevCertificateService;
import com.cenntro.oss.service.DevDeviceOnlineService;
import com.cenntro.oss.service.DevDevicePartsService;
import com.cenntro.oss.service.DevDeviceStaticService;
import com.cenntro.oss.service.DevEleService;
import com.cenntro.oss.service.SysAgentService;
import com.cenntro.oss.valid.Valid;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(value = "车辆管理", tags = { "车辆管理" })
@RestController
@RequestMapping("/device")
public class DeviceController extends BaseController {

    @Resource
    private DevDeviceStaticService devDeviceStaticService;

    @Resource
    private DevDeviceOnlineService devDeviceOnlineService;

    @Resource
    private DevCarService devCarService;

    @Resource
    private SysAgentService sysAgentService;
    
    @Resource
    private DevDevicePartsService devDevicePartsService;

    @Resource
    private DevCertificateService devCertificateService;

    @Resource
    private DevBatteryModuleService devBatteryModuleService;

    @Resource
    private DevBomCarService devBomCarService;

    @Resource
    private DevBomPartpnRefService devBomPartpnRefService;

    @Resource
    private DevBatteryPackMapper devBatteryPackMapper;

    @Resource
    private DevBatteryMapper devBatteryMapper;

    @Resource
    private AfterFaultPartsService afterFaultPartsService;

    @Resource
    private AfterFaultService afterFaultService;
    
    @Resource
    private DevDeviceStaticService deviceStaticService;

    @Resource
    private DevDeviceOnlineService deviceOnlineService;

    

    @Resource
    private DevEleService devEleService;


    /**
     * 
    * @Title list
    * @Description 车辆列表查询展示
    * @param qo
    * @return  PageResult.ok()
    * @throws
     */
    @ApiOperation(value = "车辆查询", notes = "车辆管理")
    @RequestMapping(value = "/list")
    public Result list(DeviceListQO qo, PageVO pageVO) {
        List<DeivceListVO> list = new ArrayList<DeivceListVO>();
        String agentPath = null;
        if (qo.getAgentId() != null && qo.getAgentId() > 0) {
            SysAgentDO sysAgentDO = sysAgentService.selectById(qo.getAgentId());
            agentPath = sysAgentDO == null ? null : sysAgentDO.getAgentPath();
        }
        // 管理员的权限
        Page<DevDeviceStaticDO> page = PageHelper.startPage(pageVO.getPage(), pageVO.getLimit());
        agentPath = AgentPathUtil.getAgentPathByRole(agentPath);
        qo.setAgentPath(agentPath);
        // if (qo.getAgentId() == null) {
        // list = devDeviceStaticService.staticAndOnlineAndCarList(qo);
        // } else {// 用户权限
        // String agentPath =
        // sysAgentService.agentIdConvertAgentPath(qo.getAgentId());
        // if (StringUtils.isBlank(agentPath)) {
        // return Result.error("参数错误");
        // }
        // qo.setAgentPath(agentPath + "%");
        list = devDeviceStaticService.staticAndOnlineAndCarList(qo);
        // }
        return PageResult.ok(list, page.getTotal());
    }
    
    /**
     * 车辆列表
     * 
     * @param devId
     * @return
     */
    @RequestMapping("/selectList")
    @CrossOrigin
    public Result selectList(DevListQO qo) {
        List<Integer> listdeviceStatus = new ArrayList<>();
        listdeviceStatus.add(-1);// 全部
        listdeviceStatus.add(0);// 离线
        listdeviceStatus.add(3);// 充电
        listdeviceStatus.add(5);// 熄火
        listdeviceStatus.add(24);// 启动
        if (!listdeviceStatus.contains(qo.getDeviceStatus())) {
            return Result.error("参数错误");
        }
        String agentPath = sysAgentService.agentIdConvertAgentPath(qo.getAgentId());
        if (StringUtils.isNotBlank(agentPath)) {
            qo.setAgentPath(agentPath);
            List<DeviceListVO> list = deviceStaticService.selectList(qo);
            int count = deviceStaticService.selectCountList(qo);
            return PageResult.ok(list, count);
        }
        return Result.error("agent错误");
    }

    /**
     * 
    * @Title carlist
    * @Description 车辆下拉列表
    * @param qo
    * @return  PageResult.ok()
    * @throws
     */
    @CrossOrigin
    @RequestMapping(value = "/carlist")
    public Result carlist(DeviceListQO qo, PageVO pageVO) {
        // if (qo.getAgentId() <= 0 || qo.getAgentId() == null) {
        // return Result.error("参数错误");
        // }
        // String agentPath =
        // sysAgentService.agentIdConvertAgentPath(qo.getAgentId());
        // qo.setAgentPath(agentPath);
        String agentPath = AgentPathUtil.getAgentPathByRole(null);
        Page<DevDeviceStaticDO> page = PageHelper.startPage(pageVO.getPage(), pageVO.getLimit());
        qo.setAgentPath(agentPath);
        List<DeivceListVO> list = devDeviceStaticService.staticAndOnlineAndCarList(qo);
        List<CarListVO> carList = ConvertorUtils.deepConvertList(list, CarListVO.class);
        return PageResult.ok(carList, page.getTotal());
    }

    /**
     * 
    * @Title details
    * @Description 查询车辆最新详情
    * @param devId
    * @return  Result.ok
    * @throws
     */
    @CrossOrigin
    @ApiOperation(value = "查询车辆最新详情", notes = "车辆管理")
    @RequestMapping(value = "/details")
    public Result details(Integer devId) {
        if (devId <= 0 || devId == null) {
            return Result.error("参数错误");
        }
        DeivceDetailsVO vo = devDeviceStaticService.devDetail(devId);
        return Result.ok(vo);
    }
    

    /**
     * 
    * @Title add
    * @Description 新增车辆
    * @param vehicle
    * @return  Result.ok()
    * @throws
     */
    @CrossOrigin
    @ApiOperation(value = "车辆新增", notes = "车辆管理")
    @RequestMapping(value = "/add")
    public Result add(@Validated VehicleInsertVO vehicle) {
        DevCarDO carModel = devCarService.selectById(vehicle.getCarId());
        Assert.isTrue(carModel != null, "车型不存在");
        Assert.isTrue(carModel.getStatus() != -1, "该车型已经停用");
        devDeviceStaticService.insert(vehicle);
        return Result.ok();
    }

    /**
     * 
    * @Title toAgent
    * @Description 车辆分配客户
    * @param 
    * @return  
    * @throws
     */
    @CrossOrigin
    @ApiOperation(value = "车辆分配客户", notes = "车辆分配客户")
    @RequestMapping(value = "/toAgent")
    public Result toAgent(String ids, Integer agentId) {
        String[] array = ids.split(",");
        List<Integer> idsList = Lists.transform(Lists.newArrayList(array), new Function<String, Integer>() {

            public Integer apply(String input) {
                return NumberUtils.toInt(input);
            };
        });
        return devDeviceStaticService.assign(idsList, agentId);
    }

    /**
     * 
    * @Title update
    * @Description 车辆信息修改
    * @param vehicle
    * @return  Result.ok()
    * @throws
     */
    @CrossOrigin
    @ApiOperation(value = "车辆信息修改", notes = "车辆信息修改")
    @RequestMapping(value = "/update")
    public Result update(@Validated(value = Valid.update.class) VehicleInsertVO vehicle) {
        DevDeviceStaticDO dsd = ConvertorUtils.deepConvert(vehicle, DevDeviceStaticDO.class);
        devDeviceStaticService.update(dsd);
        return Result.ok();
    }

    /**
     * 
    * @Title delete
    * @Description 车辆删除
    * @param vehicle
    * @return Result.ok
    * @throws
     */
    @CrossOrigin
    @ApiOperation(value = "车辆删除", notes = "车辆删除")
    @RequestMapping(value = "/delete")
    public Result delete(@Validated(value = Valid.update.class) VehicleInsertVO vehicle) {
        int i = devDeviceStaticService.deleteById(vehicle.getDevId());
        if (i > 0) {
            return Result.ok("删除成功");
        }
        return Result.error("删除失败");
    }

    // ----------------------------------------------------------------------------------------------------------------------------------
    /**
     * 
     * @Title selectByDevSN 
     * @Description 查询已/未选择车辆
     * @param devSN 选择车辆的devSn 
     * @return 
     * @throws
     */
    @ApiOperation(value = "序列号查询", notes = "车辆管理")
    @RequestMapping(value = "/selectByDevSN")
    public Result selectByDevSN(DeviceListQO qo) {
        if (StringUtils.isBlank(qo.getDevSN())) {
            return Result.ok();
        }
        qo.setDevSNList(Arrays.asList(qo.getDevSN().split(",")));
        List<VehicleDetailVO> list = devDeviceStaticService.selectListByUnAllot(qo);
        return PageResult.ok(list, list.size());
    }

    /**
     * 
     * @Title selectUnAllot 
     * @Description 车辆未分配查询（库存查询）
     * @param status=1
     * @return 
     */
    @ApiOperation(value = "车辆未分配查询", notes = "车辆管理")
    @RequestMapping(value = "/selectUnAllot")
    public Result selectUnAllot(DeviceListQO qo, PageVO pageVO) {
        qo.setState(1);
        qo.setDevSNList(Arrays.asList(qo.getDevSN().split(",")));
        Page<DevDeviceStaticDO> page = PageHelper.startPage(pageVO.getPage(), pageVO.getLimit());
        List<VehicleDetailVO> list = devDeviceStaticService.selectListByUnAllot(qo);
        return PageResult.ok(list, page.getTotal());
    }

    /**
     * 
     * @Title selectDetail 
     * @Description 一车一档车辆详情 
     * @param vehicle
     * @return 
     * @throws
     */
    @ApiOperation(value = "查询车辆最新详情", notes = "车辆管理")
    @RequestMapping(value = "/selectDetail")
    public Result selectDetail(VehicleVO vehicle) {
        
        Map<String, Object> map = Maps.newHashMap();
        map.put("devId", vehicle.getId());
//        map.put("vin", vehicle.getVin());
        DevDeviceStaticDO dsd = devDeviceStaticService.selectOne(map);
        DevDeviceOnlineDO dod = null;
        DevCarDO devcar = null;
        SysAgentDO sysagent = null;
        if (dsd != null) {
            Map<String, Object> columnMap = Maps.newHashMap();
            columnMap.put("devId", dsd.getDevId());
            dod = devDeviceOnlineService.selectOne(columnMap);
            devcar = devCarService.selectById(dsd.getCarId());
            sysagent = sysAgentService.selectById(dsd.getAgentId());
          
            List<VehicleDetailVO> list = devDeviceStaticService.translate(Lists.newArrayList(dsd),
                    Lists.newArrayList(dod), com.google.common.collect.Lists.newArrayList(devcar),
                    Lists.newArrayList(sysagent));
            return PageResult.ok(list.get(0));
        }
        return PageResult.error("查询错误");
    }

    /**
     * 
     * @Title 一车一档车辆过户 
     * @Description 一车一档车辆过户 
     * @param deviceStaticVO
     * @return 
     * @throws
     */
    @ApiOperation(value = "车辆分配客户", notes = "车辆分配客户")
    @RequestMapping(value = "/assign")
    public Result assign(DeviceStaticVO deviceStaticVO) {
        if (deviceStaticVO.getAgentId() == null) {
            return Result.error("客户id是空");
        }
        if (StringUtils.isBlank(deviceStaticVO.getDevSNList())) {
            return Result.error("序列号不能是空！");
        }
        return devDeviceStaticService.assign(deviceStaticVO);
    }

    /**
     * 
     * @Title selectNewDetail 
     * @Description 查询车辆最新详情替代老的详情 
     * @param devId
     * @return 
     * @throws
     */
    @CrossOrigin
    @ApiOperation(value = "查询车辆最新详情", notes = "车辆管理")
    @RequestMapping(value = "/selectNewDetail")
    public Result selectNewDetail(Integer devId) {
        Assert.isTrue(devId != null, "车辆id 不能是空！");
        // 基本信息
        VehicleVO vo = new VehicleVO();
        vo.setId(devId);
        Result result = this.selectDetail(vo);
        if (Result.SUCCESS.equals(result.getState())) {
            VehicleDetailVO detail = (VehicleDetailVO) this.selectDetail(vo).getData();
            // 零部件
            List<DevDevicePartsDO> devParts = devDevicePartsService
                    .selectByMap(ImmutableMap.of("devId", detail.getDevId()));
            DevBomPartpnRefDO ref = new DevBomPartpnRefDO();
            ref.setBomId(detail.getBomId());
            List<DevBomPartpnRefDO> refs = devBomPartpnRefService.selectPage(ref); // 关系
            List<DevDevicePartsVO> parts = fixPartsnTree(
                    ConvertorUtils.deepConvertList(devParts, DevDevicePartsVO.class), refs);
            // 合格证
            DevCertificateDO devCerts = devCertificateService.selectOne(ImmutableMap.of("devId", detail.getDevId()));
            // 电池
            DevBatteryPackDO pack = new DevBatteryPackDO();
            pack.setDevId(detail.getDevId());
            List<DevBatteryPackDO> devBatteryPackList = devBatteryPackMapper.selectPage(pack);
            List<DevBatteryPackVO> packList = ConvertorUtils.deepConvertList(devBatteryPackList,
                    DevBatteryPackVO.class);
            for (DevBatteryPackVO packVO : packList) {
                DevBatteryModuleDO module = new DevBatteryModuleDO();
                module.setDbpId(packVO.getDbpId());
                List<DevBatteryModuleDO> devBatteryModulesList = devBatteryModuleService.selectPage(module);
                List<DevBatteryModuleVO> modulesList = ConvertorUtils.deepConvertList(devBatteryModulesList,
                        DevBatteryModuleVO.class);
                packVO.setDevBatteryModuleVO(modulesList);
                for (DevBatteryModuleVO moduleVO : modulesList) {
                    DevBatteryDO battery = new DevBatteryDO();
                    battery.setDbmId(moduleVO.getDbmId());
                    List<DevBatteryDO> DevBatteryDOList = devBatteryMapper.selectPage(battery);
                    moduleVO.setDevBattery(ConvertorUtils.deepConvertList(DevBatteryDOList, DevBatteryVO.class));
                }
            }
            NewVehicleDetailVO newDetail = ConvertorUtils.deepConvert(detail, NewVehicleDetailVO.class);
            newDetail.setDevBatteryPack(packList);
            // 行驶证
//            DevDrivingInfoDO driving = devDrivingInfoService.selectOne(ImmutableMap.of("devId", detail.getDevId()));
//            newDetail.setDrivingInfo(ConvertorUtils.deepConvert(driving, DevDrivingInfoVO.class));
            // 维护记录
            AfterFaultDO afterFault = new AfterFaultDO();
            afterFault.setDevId(devId);
            List<AfterFaultDO> faultList = afterFaultService.selectPage(afterFault);
            List<AfterFaultVO> faultVOList = ConvertorUtils.deepConvertList(faultList, AfterFaultVO.class);
            for (AfterFaultVO faultVO : faultVOList) {
                AfterFaultPartsDO faultPart = new AfterFaultPartsDO();
                faultPart.setFaultId(faultVO.getFaultId());
                List<AfterFaultPartsDO> list = afterFaultPartsService.selectPage(faultPart);
                faultVO.setFaultPart(ConvertorUtils.deepConvertList(list, AfterFaultPartsVO.class));
            }
            newDetail.setAfterFault(faultVOList);
            newDetail.setDevParts(parts);
            devCerts = (devCerts == null) ? new DevCertificateDO() : devCerts;
            newDetail.setDevCerts(ConvertorUtils.deepConvert(devCerts, DevCertificateVO.class));
            return Result.ok(newDetail);
        }
        return Result.error("车辆不存在");
    }

    /**
     * 
    * @Title getchildren
    * @Description 查询所有子料号
    * @param parentPartPN 父料号
    * @param refs 关系
    * @param devParts 所有料号 
    * @return  
    * @throws
     */
    private void getchildren(DevDevicePartsVO parentPartPN, List<DevBomPartpnRefDO> refs,
            Map<String, DevDevicePartsVO> partMap) {
        Iterator<DevBomPartpnRefDO> it = refs.iterator();
        while (it.hasNext()) {
            DevBomPartpnRefDO ref = it.next();
            DevDevicePartsVO partPN = null;
            if (StringUtils.isBlank(ref.getLevel())) {
                continue;
            }
            String[] mask = ref.getLevel().split("\\.");
            if (ArrayUtils.indexOf(mask, parentPartPN.getPartsPn()) == ArrayUtils.getLength(mask) - 1) {
                if (parentPartPN.getChild() == null) {
                    parentPartPN.setChild(Lists.newArrayList());
                }
                partPN = getDevDevicePartsVO(ref, partMap.get(ref.getPartsPn()));
                parentPartPN.getChild().add(partPN);
            }
            if (partPN != null) {
                this.getchildren(partPN, refs, partMap);
            }
        }
    }

    /**
     * 
     * @param devParts
     * @param refs
     * @return
     */
    private List<DevDevicePartsVO> fixPartsnTree(List<DevDevicePartsVO> devParts, List<DevBomPartpnRefDO> refs) {
        // long st = System.currentTimeMillis();
        final List<DevDevicePartsVO> children = Lists.newArrayList();
        Map<String, DevDevicePartsVO> partMap = Maps.newHashMap();
        for (DevDevicePartsVO part : devParts) {
            part.setPartsPn(part.getPartsPn());
            partMap.put(part.getPartsPn(), part);
        }
        for (int i = 0; i < refs.size(); i++) {
            DevBomPartpnRefDO ref = refs.get(i);
            if (StringUtils.compare(ref.getLevel(), "0") == 0) {
                DevDevicePartsVO partPN = getDevDevicePartsVO(ref, partMap.get(ref.getPartsPn()));
                DevDevicePartsVO vo = getDevDevicePartsVO(ref, partPN);
                refs.remove(ref);
                children.add(vo);
                i--;
            }
        }
        for (DevDevicePartsVO partVO : children) {
            getchildren(partVO, refs, partMap);
        }
        // long end = System.currentTimeMillis();
        // System.out.println("cost" + (end - st));
        return children;
    }

    private DevDevicePartsVO getDevDevicePartsVO(DevBomPartpnRefDO ref, DevDevicePartsVO part) {
        if (part == null) {
            part = new DevDevicePartsVO();
        }
        part.setBomId(ref.getBomId());
        part.setChild(Lists.newArrayList());
        part.setPartsName(ref.getPartsName());
        part.setPartsPn(ref.getPartsPn());
        // part.setPartsSn(ref.get);
        part.setRefId(ref.getId());
        return part;
    }
    
    

    

    

    /**
     * 所属供应商下的车辆统计
     * 
     * @param agentId
     * @return
     */
    @RequestMapping("/dataCount")
    @CrossOrigin
    public Result dataCount(Integer agentId) {
        String agentPath = sysAgentService.agentIdConvertAgentPath(agentId);
        if (StringUtils.isNotEmpty(agentPath)) {
            DeviceDataCountVO vo = deviceStaticService.dataCount(agentPath);
            return Result.ok(vo);
        }
        return Result.error("agentid错误");
    }

    /**
     * 修改车辆备注名称
     * 
     * @param agentId
     * @return
     */
    @RequestMapping("/updateCarNickName")
    @CrossOrigin
    public Result updateCarNickName(Integer devId, String carNickName) {
        DevDeviceStaticDO ddo = new DevDeviceStaticDO();
        ddo.setDevId(devId);
        ddo.setCarNickName(carNickName);
        int update = deviceStaticService.update(ddo);
        if (update > 0) {
            return Result.ok();
        } else {
            return Result.error("未修改");
        }
    }

//    /**
//     * 判断此车辆是否有主副驾
//     * 
//     * @param devId
//     *            车辆id
//     * @param driverState
//     *            1.主驾 2副驾
//     * @return
//     */
//    @RequestMapping("/driver")
//    @CrossOrigin
//    public Result driver(Integer devId, Integer driverState) {
//        DevDeviceStaticDO devStatic = deviceStaticService.selectById(devId);
//        Map<String, Integer> map = new HashMap<>();
//        map.put("driverState", null);
//        if (devStatic != null && driverState != null) {
//            if (driverState == 1) {
//                if (devStatic.getMainDriverId() != null) {
//                    map.put("driverState", 1);
//                    return Result.ok(map, MessageUtil
//                            .getMsg("This vehicle has been bound to other main driver/deputy driver. Is it changed"));
//                }
//            } else if (driverState == 2) {
//                if (devStatic.getDeputyDriverId() != null) {
//                    map.put("driverState", 2);
//                    return Result.ok(map, MessageUtil
//                            .getMsg("This vehicle has been bound to other main driver/deputy driver. Is it changed"));
//                }
//            } else {
//                return Result.error("参数错误");
//            }
//        } else {
//            return Result.error("参数错误");
//        }
//        return Result.ok(map);
//    }
//
//    /**
//     * 判断司机是否绑定车辆
//     * 
//     * @param driverId
//     * @return
//     */
//    @RequestMapping("/bindDerver")
//    @CrossOrigin
//    public Result bindDerver(Integer driverId) {
//        DevDeviceStaticDO ddo = deviceStaticService.bindDerver(driverId);
//        if (ddo == null) {
//            return Result.ok(ddo);
//        }
//        return Result.ok(ddo, "司机绑定了车辆是否解除");
//    }

    /**
     * 车辆列表（地图筛选）
     * 
     * @param qo
     * @return
     */
    @RequestMapping("/carList")
    @CrossOrigin
    public Result carListMap(DeviceCarListMapQO qo) {
        if (qo.getAgentId() != null && qo.getStartUp() != null && qo.getFlameout() != null && qo.getCharge() != null
                && qo.getOffline() != null) {
            String deviceStatus = "";
            deviceStatus += qo.getStartUp().equals(1) ? "2,4" : "";
            deviceStatus += qo.getFlameout().equals(1) ? ",5" : "";
            deviceStatus += qo.getCharge().equals(1) ? ",3" : "";
            deviceStatus += qo.getOffline().equals(1) ? ",0" : "";
            deviceStatus = deviceStatus.indexOf(",") == 0 ? deviceStatus.substring(1) : deviceStatus;
            qo.setDeviceStatus(deviceStatus);
            List<DeviceCarListMapVO> showCarList = deviceStaticService.showCarList(qo);
            return PageResult.ok(showCarList, showCarList.size());
        }
        return Result.error("参数错误");
    }

    // /**
    // * 行驶轨迹
    // *
    // * @param qo
    // * @return
    // */
    // @RequestMapping("/track")
    // @CrossOrigin
    // public Result track(DeviceTrackQO qo) {
    // DevDeviceStaticDO staticDO =
    // deviceStaticService.selectById(qo.getDevId());
    // if (StringUtils.isBlank(qo.getStartTime()) && staticDO != null) {
    // return Result.error("参数错误");
    // }
    // if (StringUtils.isBlank(qo.getEndTime())) {
    // qo.setEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new
    // Date()));
    // }
    // List<DeviceTrackVO> list = deviceStaticService.selectTrack(qo);
    // return Result.ok(list);
    // }
    /**
     * 开门
     * 
     * @param qo
     * @return
     */
//    @RequestMapping("/open")
//    @CrossOrigin
//    public Result open(Integer devId, String lat, String lng) {
//        return deviceStaticService.open(devId, lat, lng);
//    }

//    /**
//     * 锁门
//     * 
//     * @param devId
//     * @return
//     */
//    @RequestMapping("/close")
//    @CrossOrigin
//    public Result close(Integer devId) {
//        return deviceStaticService.close(devId);
//    }

//    /**
//     * 变更/解除司机
//     * 
//     * @param qo
//     * @return
//     */
//    @RequestMapping("/changeDriver")
//    @CrossOrigin
//    public Result changeDriver(ChangeDriverQO qo) {
//        Integer type = deviceStaticService.change(qo);
//        if (type == 1) {
//            return Result.ok();
//        }
//        return Result.error("参数错误");
//    }

//    /**
//     * 当前行驶轨迹状态
//     * 
//     * @param
//     * @return
//     */
//    @RequestMapping("/track")
//    @ResponseBody
//    public Object getlogState(DeviceTrackVO track) {
//        Map<String, Object> resultMap = Maps.newHashMap();
//        DevDeviceStaticDO staticDO = deviceStaticService.selectById(track.getDevId());
//        DevCarDO devCarModel = devCarService.selectById(staticDO.getCarId());
//        if (track.getDevId() == null) {
//            return Result.error("车辆id不能是空！");
//        }
//        if (track.getBeginTime() == null || track.getEndTime() == null) {
//            return Result.error("时间不能是空， 请设置开始和结束时间！");
//        }
//        long sevenDay = 1000 * 60 * 60 * 24 * 7 + 1;
//        if (track.getEndTime().getTime() - track.getBeginTime().getTime() > sevenDay) {
//            return Result.error("轨迹时间超过了7天|Support for querying data for up to 7 days at most！");
//        }
//        List<TrackLogVO> trackLogs = AliTableStoreService.getInstance().getlistTrackLog(staticDO.getImei(),
//                track.getBeginTime(), track.getEndTime());
//        if (trackLogs.size() > 0) {
//            resultMap.put("trackLog", trackLogs);
//            TrackLogVO first = trackLogs.get(0);
//            TrackLogVO last = trackLogs.get(trackLogs.size() - 1);
//            // 里程是16进制转10进制 在除于10
//            Double mileage = BigDecimalUtil.subtract(last.getFaraway(), first.getFaraway()).doubleValue();
//            resultMap.put("mileage", mileage);
//            /**
//             * 使用时长/分钟
//             */
//            long usetime = (last.getCreatetime().getTime() - first.getCreatetime().getTime()) / 1000 / 60;
//            resultMap.put("usetime", usetime);
//            resultMap.put("startTime", DateFormatUtils.format(first.getCreatetime(), "MM/dd HH:mm"));
//            resultMap.put("endTime", DateFormatUtils.format(last.getCreatetime(), "MM/dd HH:mm"));
//            String startAddress = StringUtils.defaultString(first.getCity())
//                    + StringUtils.defaultString(first.getAddress());
//            String endAddress = StringUtils.defaultString(last.getCity())
//                    + StringUtils.defaultString(last.getAddress());
//            if (StringUtils.isBlank(startAddress)) {
//                startAddress = "";
//            }
//            if (StringUtils.isBlank(endAddress)) {
//                endAddress = "";
//            }
//            Integer startBattery = first.getBattery();
//            Integer endBattery = last.getBattery();
//            for (TrackLogVO trackLog : trackLogs) {
//                if (startBattery == 0 && trackLog.getBattery() > 0) {
//                    startBattery = trackLog.getBattery();
//                }
//                trackLog.setLng(trackLog.getBaidulng());
//                trackLog.setLat(trackLog.getBaidulat());
//                String time = DateFormatUtils.format(trackLog.getCreatetime(), "yyyy-MM-dd HH:mm:ss");
//                trackLog.setTime(time);
//                if (devCarModel != null) {
//                    trackLog.setHavaKm(CarUtil.getHavaKm(trackLog.getBattery(), devCarModel.getLife()) + "");
//                }
//                String runAwary = BigDecimalUtil.subtract(trackLog.getFaraway(), first.getFaraway()).setScale(2)
//                        .toString();
//                trackLog.setRunAwary(runAwary);
//            }
//            Map<String, Object> map = ImmutableMap.of("imei", staticDO.getImei(), "startTime", first.getCreatetime(),
//                    "endTime", last.getCreatetime());
//            DevEleDO ele = devEleService.selectCharging(map);
//            if (ele != null) {
//                startBattery += ele.getUpBattery();
//            }
//            /**
//             * 消耗电量
//             */
//            Double losspower = (startBattery - endBattery) * Double.valueOf(devCarModel.getBattery()) / 100;
//            resultMap.put("losspower", losspower);
//            resultMap.put("startAddress", startAddress);
//            resultMap.put("endAddress", endAddress);
//            if (StringUtils.isBlank(startAddress)) {
//                String[] str = GpsTrasformUtil.gps2Address(first.getBaidulng(), first.getBaidulat());
//                for (String st : str) {
//                    if (StringUtils.isNotBlank(st)) {
//                        startAddress += st;
//                    }
//                }
//                resultMap.put("startAddress", startAddress);
//            }
//            if (StringUtils.isBlank(endAddress)) {
//                String[] str = GpsTrasformUtil.gps2Address(last.getBaidulng(), last.getBaidulat());
//                for (String st : str) {
//                    if (StringUtils.isNotBlank(st)) {
//                        endAddress += st;
//                    }
//                }
//                resultMap.put("endAddress", endAddress);
//            }
//            double km100loss = CarUtil.get100Kmloss(mileage, startBattery - endBattery);
//            resultMap.put("hundredloss", km100loss);
//        }
//        return Result.ok(resultMap);
//    }
    
    
    
}
